package com.iron.common.feign.logger;

import feign.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * 自定义 feign 日志类 ，使用 info 等级
 * 使用 slf4j 代替 feign logging 进行日志打印
 *
 * @author YT
 * @date 2019-06-11
 */
public class IronFeignLogger extends feign.Logger {

    private final Logger logger;

    public IronFeignLogger() {
        this(feign.Logger.class);
    }

    public IronFeignLogger(Class<?> clazz) {
        this(LoggerFactory.getLogger(clazz));
    }

    public IronFeignLogger(String name) {
        this(LoggerFactory.getLogger(name));
    }

    public IronFeignLogger(Logger logger) {
        this.logger = logger;
    }

    @Override
    protected Response logAndRebufferResponse(String configKey, Level logLevel, Response response, long elapsedTime) throws IOException {
        if (logger.isInfoEnabled()) {
            return super.logAndRebufferResponse(configKey, logLevel, response, elapsedTime);
        }
        return response;
    }

    /**
     * 根据判断条件可以改变 feign 日志的打印等级
     *
     * @param configKey
     * @param format
     * @param args
     */
    @Override
    protected void log(String configKey, String format, Object... args) {
        if (logger.isInfoEnabled()) {
            logger.info(String.format(methodTag(configKey) + format, args));
        }
    }
}
